<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input id="file" type="file" />
    <script>
        const file = document.getElementById('file')

        function createChunks(file, chunkSize) {
            const result = [];
            for (let i = 0; i < file.size; i += chunkSize) {
                result.push(file.slice(i, i + chunkSize));

            }
            return result;
        }
        const uploadFile = (chunks,fileName) => {
            // 批量上传 promise.all [请求 请求 请求]
            // formData 上传file，标识hash/index
            const list = [];
            for (let i = 0; i < chunks.length; i++) {
                const formData = new FormData();
                formData.append('index', i); //添加标识
                formData.append('fileName', "chunk");
                formData.append('total', chunks.length);
                const blob = chunks[i]
                formData.append('file', blob); //一定写在最后
                list.push(fetch("http://localhost:3000/partUpload", {
                    method: "POST",
                    body: formData
                }))
            }
            Promise.all(list).then(res => {
                // 切片上传完毕后通知后端合并切片
                fetch("http://localhost:3000/merge",{
                    method:"POST",
                    headers:{
                        "Content-Type":"application/json"
                    },
                    body:JSON.stringify({
                        fileName:fileName
                    })
                })
                console.log("上传成功", res);
            })
        }

        file.addEventListener('change', async (event) => {
            const file = event.target.files[0] //获取文件对象，底层继承于Blob，调用slice切割

            const chunks = createChunks(file, 1 << 20) // 切片
            const a = await uploadFile(chunks,file.name);
        })
    </script>
</body>

</html>